import java.util.concurrent.PriorityBlockingQueue;

public class RewriteTimer {
    //重写定时器
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务1");
            }
        }, 2000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务2");
            }
        }, 1000);
    }
}
class MyTimer{
    //扫描线程
    private Thread t=null;
    //带优先级的阻塞队列
    private   PriorityBlockingQueue<MyTask>priorityBlockingQueue=new PriorityBlockingQueue();
    //进行等待
    private Object locker=new Object();

    public MyTimer() {
        t=new Thread(){
            //取出队首元素查看是否到时间，如果到了就执行
            //没到时间就把元素插回去
            public void run(){
                while(true){
                    try{
                        System.out.println("this2"+this);
                        synchronized (locker){
                            MyTask myTask=priorityBlockingQueue.take();
                            long curTime=System.currentTimeMillis();
                            if(curTime<myTask.getTime()){
                                priorityBlockingQueue.put(myTask);
                                locker.wait(myTask.getTime() - curTime);
                            }else{
                                myTask.run();
                            }
                        }
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();
    }
    //两个参数
    //一个是要执行的代码
    //一个是要等待的时间长短
    public void schedule(Runnable runnable,long after){
        MyTask task=new MyTask(runnable,System.currentTimeMillis()+after);
        priorityBlockingQueue.put(task);
        System.out.println("this1"+this);
        synchronized (locker){
            locker.notify();
        }
    }
}

//一个定时器中的任务
class MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time;
    }
    public long getTime() {
        return time;
    }

    // 执行任务
    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTask o) {

        return (int) (this.time - o.time);
    }
}